<template>
  <div>
    <!-- 顶部面包屑标识与导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>客户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <!-- 操作区域 -->
    <div style="margin: 0 0 20px 0;">
      <el-button type="primary" size="medium" @click="$router.push('/service/customer/add')">添加客户</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
      <el-table-column prop="user" label="名称" width="80" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="180" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="departmentName" label="科室" width="80" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="appointment" label="预约时间" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="patient_history" label="患病史" width="180" header-align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="description" label="病情描述" width="80" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="address" label="住址" width="80" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="state" label="状态" width="80" align="center"
                       :show-overflow-tooltip="true"></el-table-column>

      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" circle
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" circle
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div style="margin: 10px 0; text-align: right;">
      <el-pagination
          @current-change="changePage"
          :hide-on-single-page="true"
          :page-size="pageSize"
          :current-page="currentPage"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <!-- 修改客户信息的弹出表单Dialog -->
    <el-dialog title="修改客户信息" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="editRules" :label-width="formLabelWidth">
        <el-form-item label="名称" prop="user">
          <el-input v-model="editForm.user"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="科室" prop="departmentName">
          <template>
            <el-select v-model="editForm.departmentId" placeholder="请选择">
              <el-option
                  v-for="item in departmentData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointment">
          <template>
              <el-date-picker
                  v-model="date"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd">
              </el-date-picker>
              <el-time-select
                  v-model="time"
                  :picker-options="{start:'08:30',step:'00:15',end: '21:30'}"
                  placeholder="选择时间">
              </el-time-select>
          </template>
        </el-form-item>
        <el-form-item label="病史" prop="patient_history">
          <el-input v-model="editForm.patient_history"></el-input>
        </el-form-item>
        <el-form-item label="病情描述" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input v-model="editForm.address"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-input v-model="editForm.state"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      date: '2023-06-01',
      time: '08:30',
      // 表格数据
      tableData: [],
      //科室选择表
      departmentData: [],
      // 分页相关数据
      currentPage: this.$router.currentRoute.query.page ? parseInt(this.$router.currentRoute.query.page) : 1,
      pageSize: 20,
      pageCount: 1,
      total: 0,
      // 编辑对话框的可见性
      dialogFormVisible: false,
      // 编辑表单
      editForm: {
        id: 0,
        user: '',
        phone:'',
        departmentName: '',
        departmentId:0,
        appointment: '',
        patient_history: '',
        description: '',
        address: '',
        state:'',
      },
      // 编辑表单的验证规则
      editRules: {
        user: [
          {required: true, message: '请输入客户名称', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入客户电话', trigger: 'blur'},
          {min: 4, max: 25, message: '长度在 4 到 25 个字符', trigger: 'blur'}
        ],
        departmentId: [
          {required: true, message: '请输入科室', trigger: 'blur'},
        ],
        patient_history: [
          {required: true, message: '请输入患病历史', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'}
        ],
        appointment: [
          {required: true, message: '请输入客户预约时间', trigger: 'blur'},
          {min: 0, max: 255, message: '长度不限', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入病情描述', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请输入客户住址', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
        ],
        state: [
          {required: true, message: '请输入客户状态', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
        ]
      },

      // 编辑表单的label宽度
      formLabelWidth: '120px'
    }
  },
  methods: {
    // 打开编辑对话框
    openEditDialog(customer) {
      console.log(this.departmentData);
      let url = 'http://localhost:9999/customers/' + customer.id+'/update';
      console.log('url = ' + url);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    // 提交编辑表单
    submitEditForm() {
      for (let i = 0; i < this.departmentData.length; i++) {
        if (this.departmentData[i].id === this.editForm.departmentId) {
          this.editForm.departmentName = this.departmentData[i].name;
          break;
        }
      }
      this.editForm.appointment = this.date +' '+this.time+':00';
      let url = 'http://localhost:9999/customers/' + this.editForm.id + '/update';
      console.log('url = ' + url);

      let formData = this.qs.stringify(this.editForm);
      console.log('formData = ' + formData);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '修改客户信息成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadCustomerList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadCustomerList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$message.error(jsonResult.message);
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
            }
          });
        }
      });
    },
    // 打开删除确认框
    openDeleteConfirm(customer) {
      let title = '提示';
      let message = '此操作将永久删除【' + customer.user + '】客户信息，是否继续？';
      this.$confirm(message, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(customer);
      }).catch(() => {
      });
    },
    // 处理删除
    handleDelete(customer) {
      let url = 'http://localhost:9999/customers/' + customer.id + '/delete';
      console.log('url = ' + url);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除客户信息【' + customer.user + '】成功！',
            type: 'success'
          });
          this.loadCustomerList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCustomerList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    // 切换分页
    changePage(page) {
      this.$router.replace('?page=' + page);
      this.loadCustomerList();
    },
    // 加载客户信息列表
    loadCustomerList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }

      let url = 'http://localhost:9999/customers?page=' + page;
      console.log('url = ' + url);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .get(url).then((response) => {
        let jsonResult = response.data;

        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.currentPage = jsonResult.data.currentPage;
          this.pageSize = jsonResult.data.pageSize;
          this.pageCount = jsonResult.data.maxPage;
          this.total = jsonResult.data.total;
        }
      });
    },
    loadDepartmentList() {
      let url = 'http://localhost:9999/departments?page=1&queryType='+'all';
      console.log('url = ' + url);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .get(url).then((response) => {
        let jsonResult = response.data;

        if (jsonResult.state == 20000) {
          this.departmentData = jsonResult.data.list;
        }
      });
    }

  },
  mounted() {
    this.loadCustomerList();
    this.loadDepartmentList();
  }
}
</script>

<style scoped>

</style>
